package com.example.api.service.impl;

import com.example.api.dao.CodeDao;
import com.example.api.model.entity.Code;
import com.example.api.service.EmailService;
import com.example.api.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Objects;

@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private CodeDao codeDao;

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendVerificationCode(String email) throws MailException {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email);
        message.setSubject("验证码");
        String value = RandomUtil.next();
        message.setText("你的验证码为:  " + value + "  五分钟内有效");
        mailSender.send(message);
        //保存验证码
        Code code = new Code();
        code.setEmail(email);
        code.setValue(value);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(GregorianCalendar.MINUTE, 5);
        code.setExpireTime(calendar.getTime());
        codeDao.insertSelective(code);
    }

    @Override
    public Boolean checkVerificationCode(String email, String value) {
        Code code = codeDao.findByEmailAndValue(email, value);
        if (Objects.nonNull(code) && code.getExpireTime().after(new Date())) {
            //登陆成功删除验证码
            codeDao.deleteByPrimaryKey(code.getEmail());
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}